<?php

/**
 * TransferPreviewApi
 * PHP version 8.3.
 *
 * @category Class
 *
 * @author   OpenAPI Generator team
 *
 * @see     https://openapi-generator.tech
 */

/**
 * The Selling Partner API for Amazon Seller Wallet Open Banking API.
 *
 * The Selling Partner API for Seller Wallet (Seller Wallet API) provides financial information that is relevant to a seller's Seller Wallet account. You can obtain financial events, balances, and transfer schedules for Seller Wallet accounts. You can also schedule and initiate transactions.
 *
 * The version of the OpenAPI document: 2024-03-01
 * Generated by: https://openapi-generator.tech
 * Generator version: 7.9.0
 */

/**
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

namespace SpApi\Api\sellerWallet\v2024_03_01;

use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
use SpApi\ApiException;
use SpApi\AuthAndAuth\RestrictedDataTokenSigner;
use SpApi\Configuration;
use SpApi\HeaderSelector;
use SpApi\Model\sellerWallet\v2024_03_01\TransferRatePreview;
use SpApi\ObjectSerializer;
use Symfony\Component\RateLimiter\LimiterInterface;
use Symfony\Component\RateLimiter\RateLimiterFactory;
use Symfony\Component\RateLimiter\Storage\InMemoryStorage;

/**
 * TransferPreviewApi Class Doc Comment.
 *
 * @category Class
 *
 * @author   OpenAPI Generator team
 *
 * @see     https://openapi-generator.tech
 */
class TransferPreviewApi
{
    public ?LimiterInterface $getTransferPreviewRateLimiter;
    protected ClientInterface $client;

    protected Configuration $config;

    protected HeaderSelector $headerSelector;

    /**
     * @var int Host index
     */
    protected int $hostIndex;

    private bool $rateLimiterEnabled;
    private InMemoryStorage $rateLimitStorage;

    /**
     * @param int $hostIndex (Optional) host index to select the list of hosts if defined in the OpenAPI spec
     */
    public function __construct(
        Configuration $config,
        ?ClientInterface $client = null,
        ?bool $rateLimiterEnabled = true,
        ?HeaderSelector $selector = null,
        int $hostIndex = 0
    ) {
        $this->config = $config;
        $this->rateLimiterEnabled = $rateLimiterEnabled;

        if ($rateLimiterEnabled) {
            $this->rateLimitStorage = new InMemoryStorage();

            $factory = new RateLimiterFactory(Configuration::getRateLimitOptions('TransferPreviewApi-getTransferPreview'), $this->rateLimitStorage);
            $this->getTransferPreviewRateLimiter = $factory->create('TransferPreviewApi-getTransferPreview');
        }

        $this->client = $client ?: new Client();
        $this->headerSelector = $selector ?: new HeaderSelector();
        $this->hostIndex = $hostIndex;
    }

    /**
     * Set the host index.
     *
     * @param int $hostIndex Host index (required)
     */
    public function setHostIndex(int $hostIndex): void
    {
        $this->hostIndex = $hostIndex;
    }

    /**
     * Get the host index.
     *
     * @return int Host index
     */
    public function getHostIndex(): int
    {
        return $this->hostIndex;
    }

    public function getConfig(): Configuration
    {
        return $this->config;
    }

    /**
     * Operation getTransferPreview.
     *
     * Fetch potential fees that could be applied on a transaction on the basis of the source and destination country currency code
     *
     * @param string      $source_country_code
     *                                               Represents 2 character country code of source transaction account in ISO 3166 standard format. (required)
     * @param string      $source_currency_code
     *                                               Represents 3 letter currency code in ISO 4217 standard format of the source transaction country. (required)
     * @param string      $destination_country_code
     *                                               Represents 2 character country code of destination transaction account in ISO 3166 standard format. (required)
     * @param string      $destination_currency_code
     *                                               Represents 3 letter currency code in ISO 4217 standard format of the destination transaction country. (required)
     * @param float       $base_amount
     *                                               Represents the base transaction amount without any markup fees, rates that will be used to get the transfer preview. (required)
     * @param null|string $restrictedDataToken       Restricted Data Token (RDT) for accessing restricted resources (optional, required for operations that return PII)
     *
     * @throws ApiException              on non-2xx response
     * @throws \InvalidArgumentException
     */
    public function getTransferPreview(
        string $source_country_code,
        string $source_currency_code,
        string $destination_country_code,
        string $destination_currency_code,
        float $base_amount,
        ?string $restrictedDataToken = null
    ): TransferRatePreview {
        list($response) = $this->getTransferPreviewWithHttpInfo($source_country_code, $source_currency_code, $destination_country_code, $destination_currency_code, $base_amount, $restrictedDataToken);

        return $response;
    }

    /**
     * Operation getTransferPreviewWithHttpInfo.
     *
     * Fetch potential fees that could be applied on a transaction on the basis of the source and destination country currency code
     *
     * @param string      $source_country_code
     *                                               Represents 2 character country code of source transaction account in ISO 3166 standard format. (required)
     * @param string      $source_currency_code
     *                                               Represents 3 letter currency code in ISO 4217 standard format of the source transaction country. (required)
     * @param string      $destination_country_code
     *                                               Represents 2 character country code of destination transaction account in ISO 3166 standard format. (required)
     * @param string      $destination_currency_code
     *                                               Represents 3 letter currency code in ISO 4217 standard format of the destination transaction country. (required)
     * @param float       $base_amount
     *                                               Represents the base transaction amount without any markup fees, rates that will be used to get the transfer preview. (required)
     * @param null|string $restrictedDataToken       Restricted Data Token (RDT) for accessing restricted resources (optional, required for operations that return PII)
     *
     * @return array of \SpApi\Model\sellerWallet\v2024_03_01\TransferRatePreview, HTTP status code, HTTP response headers (array of strings)
     *
     * @throws ApiException              on non-2xx response
     * @throws \InvalidArgumentException
     */
    public function getTransferPreviewWithHttpInfo(
        string $source_country_code,
        string $source_currency_code,
        string $destination_country_code,
        string $destination_currency_code,
        float $base_amount,
        ?string $restrictedDataToken = null
    ): array {
        $request = $this->getTransferPreviewRequest($source_country_code, $source_currency_code, $destination_country_code, $destination_currency_code, $base_amount);
        if (null !== $restrictedDataToken) {
            $request = RestrictedDataTokenSigner::sign($request, $restrictedDataToken, 'TransferPreviewApi-getTransferPreview');
        } else {
            $request = $this->config->sign($request);
        }

        try {
            $options = $this->createHttpClientOption();

            try {
                if ($this->rateLimiterEnabled) {
                    $this->getTransferPreviewRateLimiter->consume()->ensureAccepted();
                }
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getResponse()->getBody()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }
            if ('\SpApi\Model\sellerWallet\v2024_03_01\TransferRatePreview' === '\SplFileObject') {
                $content = $response->getBody(); // stream goes to serializer
            } else {
                $content = (string) $response->getBody();
                if ('\SpApi\Model\sellerWallet\v2024_03_01\TransferRatePreview' !== 'string') {
                    $content = json_decode($content);
                }
            }

            return [
                ObjectSerializer::deserialize($content, '\SpApi\Model\sellerWallet\v2024_03_01\TransferRatePreview', []),
                $response->getStatusCode(),
                $response->getHeaders(),
            ];
        } catch (ApiException $e) {
            $data = ObjectSerializer::deserialize(
                $e->getResponseBody(),
                '\SpApi\Model\sellerWallet\v2024_03_01\ErrorList',
                $e->getResponseHeaders()
            );
            $e->setResponseObject($data);

            throw $e;
        }
    }

    /**
     * Operation getTransferPreviewAsync.
     *
     * Fetch potential fees that could be applied on a transaction on the basis of the source and destination country currency code
     *
     * @param string $source_country_code
     *                                          Represents 2 character country code of source transaction account in ISO 3166 standard format. (required)
     * @param string $source_currency_code
     *                                          Represents 3 letter currency code in ISO 4217 standard format of the source transaction country. (required)
     * @param string $destination_country_code
     *                                          Represents 2 character country code of destination transaction account in ISO 3166 standard format. (required)
     * @param string $destination_currency_code
     *                                          Represents 3 letter currency code in ISO 4217 standard format of the destination transaction country. (required)
     * @param float  $base_amount
     *                                          Represents the base transaction amount without any markup fees, rates that will be used to get the transfer preview. (required)
     *
     * @throws \InvalidArgumentException
     */
    public function getTransferPreviewAsync(
        string $source_country_code,
        string $source_currency_code,
        string $destination_country_code,
        string $destination_currency_code,
        float $base_amount
    ): PromiseInterface {
        return $this->getTransferPreviewAsyncWithHttpInfo($source_country_code, $source_currency_code, $destination_country_code, $destination_currency_code, $base_amount)
            ->then(
                function ($response) {
                    return $response[0];
                }
            )
        ;
    }

    /**
     * Operation getTransferPreviewAsyncWithHttpInfo.
     *
     * Fetch potential fees that could be applied on a transaction on the basis of the source and destination country currency code
     *
     * @param string $source_country_code
     *                                          Represents 2 character country code of source transaction account in ISO 3166 standard format. (required)
     * @param string $source_currency_code
     *                                          Represents 3 letter currency code in ISO 4217 standard format of the source transaction country. (required)
     * @param string $destination_country_code
     *                                          Represents 2 character country code of destination transaction account in ISO 3166 standard format. (required)
     * @param string $destination_currency_code
     *                                          Represents 3 letter currency code in ISO 4217 standard format of the destination transaction country. (required)
     * @param float  $base_amount
     *                                          Represents the base transaction amount without any markup fees, rates that will be used to get the transfer preview. (required)
     *
     * @throws \InvalidArgumentException
     */
    public function getTransferPreviewAsyncWithHttpInfo(
        string $source_country_code,
        string $source_currency_code,
        string $destination_country_code,
        string $destination_currency_code,
        float $base_amount,
        ?string $restrictedDataToken = null
    ): PromiseInterface {
        $returnType = '\SpApi\Model\sellerWallet\v2024_03_01\TransferRatePreview';
        $request = $this->getTransferPreviewRequest($source_country_code, $source_currency_code, $destination_country_code, $destination_currency_code, $base_amount);
        if (null !== $restrictedDataToken) {
            $request = RestrictedDataTokenSigner::sign($request, $restrictedDataToken, 'TransferPreviewApi-getTransferPreview');
        } else {
            $request = $this->config->sign($request);
        }
        if ($this->rateLimiterEnabled) {
            $this->getTransferPreviewRateLimiter->consume()->ensureAccepted();
        }

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    if ('\SplFileObject' === $returnType) {
                        $content = $response->getBody(); // stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ('string' !== $returnType) {
                            $content = json_decode($content);
                        }
                    }

                    return [
                        ObjectSerializer::deserialize($content, $returnType, []),
                        $response->getStatusCode(),
                        $response->getHeaders(),
                    ];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();

                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            )
        ;
    }

    /**
     * Create request for operation 'getTransferPreview'.
     *
     * @param string $source_country_code
     *                                          Represents 2 character country code of source transaction account in ISO 3166 standard format. (required)
     * @param string $source_currency_code
     *                                          Represents 3 letter currency code in ISO 4217 standard format of the source transaction country. (required)
     * @param string $destination_country_code
     *                                          Represents 2 character country code of destination transaction account in ISO 3166 standard format. (required)
     * @param string $destination_currency_code
     *                                          Represents 3 letter currency code in ISO 4217 standard format of the destination transaction country. (required)
     * @param float  $base_amount
     *                                          Represents the base transaction amount without any markup fees, rates that will be used to get the transfer preview. (required)
     *
     * @throws \InvalidArgumentException
     */
    public function getTransferPreviewRequest(
        string $source_country_code,
        string $source_currency_code,
        string $destination_country_code,
        string $destination_currency_code,
        float $base_amount
    ): Request {
        // verify the required parameter 'source_country_code' is set
        if (null === $source_country_code || (is_array($source_country_code) && 0 === count($source_country_code))) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $source_country_code when calling getTransferPreview'
            );
        }
        // verify the required parameter 'source_currency_code' is set
        if (null === $source_currency_code || (is_array($source_currency_code) && 0 === count($source_currency_code))) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $source_currency_code when calling getTransferPreview'
            );
        }
        // verify the required parameter 'destination_country_code' is set
        if (null === $destination_country_code || (is_array($destination_country_code) && 0 === count($destination_country_code))) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $destination_country_code when calling getTransferPreview'
            );
        }
        // verify the required parameter 'destination_currency_code' is set
        if (null === $destination_currency_code || (is_array($destination_currency_code) && 0 === count($destination_currency_code))) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $destination_currency_code when calling getTransferPreview'
            );
        }
        // verify the required parameter 'base_amount' is set
        if (null === $base_amount || (is_array($base_amount) && 0 === count($base_amount))) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $base_amount when calling getTransferPreview'
            );
        }

        $resourcePath = '/finances/transfers/wallet/2024-03-01/transferPreview';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;

        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $source_country_code,
            'sourceCountryCode', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            true, // required
            $this->config
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $source_currency_code,
            'sourceCurrencyCode', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            true, // required
            $this->config
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $destination_country_code,
            'destinationCountryCode', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            true, // required
            $this->config
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $destination_currency_code,
            'destinationCurrencyCode', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            true, // required
            $this->config
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $base_amount,
            'baseAmount', // param base name
            'number', // openApiType
            '', // style
            false, // explode
            true, // required
            $this->config
        ) ?? []);

        $headers = $this->headerSelector->selectHeaders(
            ['application/json'],
            '',
            $multipart
        );

        // for model (json/xml)
        if (count($formParams) > 0) {
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem,
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);
            } elseif ('application/json' === $headers['Content-Type']) {
                $httpBody = \GuzzleHttp\json_encode($formParams);
            } else {
                // for HTTP post (form)
                $httpBody = ObjectSerializer::buildQuery($formParams, $this->config);
            }
        }

        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $query = ObjectSerializer::buildQuery($queryParams, $this->config);

        return new Request(
            'GET',
            $this->config->getHost().$resourcePath.($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Create http client option.
     *
     * @return array of http client options
     *
     * @throws \RuntimeException on file opening failure
     */
    protected function createHttpClientOption(): array
    {
        $options = [];
        if ($this->config->getDebug()) {
            $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a');
            if (!$options[RequestOptions::DEBUG]) {
                throw new \RuntimeException('Failed to open the debug file: '.$this->config->getDebugFile());
            }
        }

        return $options;
    }
}
